using System;
using System.Collections.Generic;
using System.Text;

namespace LoanPrequalificationSystem.Model.Products
{
    public class ProductService
    {
        private IProductRepository productRepository;

        public ProductService(IProductRepository productRepository)
        {
            this.productRepository = productRepository;
        }

        public Product FindProductById(Guid productId)
        {
            var prodcut = productRepository.FindBy(productId);

            if (prodcut == null)
                throw new Exception(String.Format("Can't find product with ID '{0}'", productId.ToString()));

            return prodcut;
        }


        public void Save(Product product)
        {
            if (product.GetBrokenRules().Count > 0)
            {
                throw new Exception(
                    String.Format("This product is invalid and cannot be saved in its present state. '{0}'",
                                  GetBrokenRulesToStringFor(product.GetBrokenRules())));
            }
            productRepository.Save(product);
        }

        public List<Product> FindAll()
        {
            return productRepository.FindAll();
        }

        private string GetBrokenRulesToStringFor(List<BrokenBusinessRule> brokenRules)
        {
            var sbBrokenRules = new StringBuilder();

            foreach (var brokenBusinessRule in brokenRules)
            {
                sbBrokenRules.Append(brokenBusinessRule.Rule);
            }
            return sbBrokenRules.ToString();
        }
    }
}